/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/convert-binary-tree-to-linked-lists-by-depth
   @Language: C++
   @Datetime: 19-06-25 09:30
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	/**
	 * @param root the root of binary tree
	 * @return a lists of linked list
	 */
	vector<ListNode*> binaryTreeToLists(TreeNode* root) {
		// Write your code here
		vector<ListNode*> v;
		queue<TreeNode*> q;
		for(q.push(root); q.size();){
			ListNode H(-1), *p=&H;
			for(int size=q.size(); size--; q.pop()){
				TreeNode *r=q.front();
				if(r==NULL) continue;
				p=p->next=new ListNode(r->val);
				if(r->left) q.push(r->left);
				if(r->right) q.push(r->right);
			}
			if(H.next) v.push_back(H.next);
		}
		return v;
	}
};
